package com.example.chatservice.webSocket.netty;


import com.easychat.mychat.ChannelContextUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.example.config.redis.RedisComponent;
import org.example.entity.dto.TokenUserInfoDto;
import org.example.utils.StringTools;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description
 * @Author susu
 * @Date 2024/9/18
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class HandlerWebSocket extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Resource
    private RedisComponent redisComponent;

    @Resource
    private ChannelContextUtils channelContextUtils;

    //通道就绪后调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("有新的连接加入....");

    }
    //连接断开后 执行此方法
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接断开");
//        redisComponent.
        Channel channel = ctx.channel();
        String string = channel.id().toString();
        String userId = (String) channel.attr(AttributeKey.valueOf(string)).get();
        channelContextUtils.removeContext(userId);
    }

    //收到信息后调用此接口
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        Channel channel = ctx.channel();
        Attribute<String> attr = channel.attr(AttributeKey.valueOf(channel.id().toString()));
        String userId = attr.get();
        log.info("收到{}消息{}",userId,textWebSocketFrame.text());
        redisComponent.saveHeartBeat(userId);
        //收到消息后发到群组

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete){
            WebSocketServerProtocolHandler.HandshakeComplete complete = (WebSocketServerProtocolHandler.HandshakeComplete)evt;
            String url = complete.requestUri();
//            log.info("url{}",url);
            String token = getToken(url);
            if (token == null){
                ctx.channel().close();
                return;
            }
            TokenUserInfoDto dto = redisComponent.getTokenUserInfoDto(token);
            if (dto == null){
                ctx.channel().close();
                return;
            }
            channelContextUtils.addContext(dto.getUserId(),ctx.channel());
        }
    }

    //解析url
    private String getToken(String url){
        if (StringTools.isEmpty(url) || url.indexOf("?") == -1){
            return null;
        }
        String[] queryParams = url.split("\\?");
        if (queryParams.length != 2){
            return null;
        }
        String[] split = queryParams[1].split("=");
        if (split[1].isEmpty()){
            return null;
        }
        return split[1];
    }
}
